package com.hxl.tech.gateway.auth.controller;

import com.hxl.tech.gateway.auth.annotate.ApiPrivilege;
import com.hxl.tech.gateway.auth.dto.Response;
import com.hxl.tech.gateway.auth.dto.openapi.OpenApiDTO;
import com.hxl.tech.gateway.auth.dto.openapi.OpenApiDeleteDTO;
import com.hxl.tech.gateway.auth.dto.openapi.OpenApiFindDTO;
import com.hxl.tech.gateway.auth.dto.openapi.OpenApiSaveDTO;
import com.hxl.tech.gateway.auth.model.OpenApi;
import com.hxl.tech.gateway.auth.service.OpenApiService;
import com.hxl.tech.gateway.auth.util.CopyUtil;
import com.hxl.tech.gateway.common.constant.AppConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 开放接口 Controller 
 * @author soliddq
 * @date 2023-10-10
 */
@Api(value = "接口管理", tags = "接口管理")
@RestController
@RequiredArgsConstructor
public class OpenApiController {

    private final OpenApiService openApiService;

    @ApiPrivilege(needRole = AppConstant.ROLE_ADMIN)
    @GetMapping("gateway.auth.api.module.list")
    @ApiOperation(value = "查询接口模块列表", response = String.class)
    public Response listApiModule() {

        List<OpenApi> openApis = openApiService.find(new OpenApiFindDTO());
        List<String> modules = openApis.stream().map(OpenApi::getApiModule).distinct().collect(Collectors.toList());
        return Response.createSuccess(modules);
    }

    @ApiPrivilege(needRole = AppConstant.ROLE_ADMIN)
    @PostMapping("gateway.auth.api.name.list")
    @ApiOperation(value = "查询接口名称列表", response = String.class)
    public Response listApiName(@RequestBody @Validated OpenApiFindDTO findDTO) {

        List<OpenApi> openApis = openApiService.find(findDTO);
        List<String> apis = openApis.stream().map(OpenApi::getApiName).distinct().collect(Collectors.toList());
        return Response.createSuccess(apis);
    }

    @ApiPrivilege(needRole = AppConstant.ROLE_ADMIN)
    @PostMapping("gateway.auth.api.save")
    @ApiOperation(value = "新增开放接口", response = OpenApiDTO.class)
    public Response saveApi(@RequestBody @Validated OpenApiSaveDTO saveDTO) {

        return Response.createSuccess(CopyUtil.to(openApiService.saveOrUpdate(CopyUtil.to(saveDTO, OpenApi.class)), OpenApiDTO.class));
    }

    @ApiPrivilege(needRole = AppConstant.ROLE_ADMIN)
    @PostMapping("gateway.auth.api.delete")
    @ApiOperation(value = "删除开放接口", response = String.class)
    public Response deleteApi(@RequestBody @Validated OpenApiDeleteDTO deleteDTO) {

        openApiService.delete(deleteDTO.getApiName());
        return Response.createSuccess();
    }
}
